﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SocketTEST
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress address = IPAddress.Loopback;
            IPEndPoint endPoint = new IPEndPoint(address, 49152);
            Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sk.Bind(endPoint);
            sk.Listen(10);
            Console.WriteLine("开始监听端口号：{0}",endPoint.Port);
            while (true)
            {
                Socket client = sk.Accept();

                Console.WriteLine(client.RemoteEndPoint);

                byte[] buffer = new byte[4096];

                int length = client.Receive(buffer, 4096, SocketFlags.None);

                System.Text.Encoding utf8 = System.Text.Encoding.UTF8;

                string requestString = utf8.GetString(buffer, 0, length);

                Console.WriteLine(requestString);

                string statusLine = "HTTP/1.1 200 OK\r\n";

                byte[] statusLineBytes = utf8.GetBytes(statusLine);

                string responseBody = "<html><head><title>From Socket Server</title></head><body><h1>Hello,word!</h1></body></html>";
                byte[] responseBodyBytes = utf8.GetBytes(responseBody);

                string responseHeader=string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n",responseBody.Length);

                byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);

                client.Send(statusLineBytes);

                client.Send(responseHeaderBytes);

                client.Send(new byte[]{13,10});

                client.Send(responseHeaderBytes);

                client.Close();

                if (Console.KeyAvailable)
                {
                    break;
                }
            }

            sk.Close();
        }
    }
}
